// pages/user_home/user_home.js
const handler = require("../../utils/function.js");
var api = require("../../api.js"),
  QQMapWX = require("../../utils/qqmap-wx.js"),
  app = getApp();
var demo = new QQMapWX({
  key: 'EKJBZ-72L3P-FHXDL-VSLEP-JEAGJ-JTFSD' // 必填
});
Component({
  properties: {
    paramA: Number,
    paramB: String,
  },
  data: {

    home_show_class: "home_container_right",
    img: handler.userImg,
    markers: {},
    polyline: [{
      points: [],
      color: "#0299de",
      width: 9,
      dottedLine: false,
      arrowLine: true,
    },
    ],
    controls: [{
      id: 1,
      iconPath: '/images/user/icon-22.png',
      position: {
        left: 10,
        top: 10,
        width: 50,
        height: 50
      },
      clickable: true
    }], //人物图片定位
    drivers: [{
      id: "001",
      title: "1名司机"
    }, {
      id: "002",
      title: "2名司机"
    }, {
      id: "003",
      title: "3名司机"
    }, {
      id: "004",
      title: "4名司机"
    }, {
      id: "005",
      title: "5名司机"
    }, {
      id: "006",
      title: "6名司机"
    }, {
      id: "007",
      title: "7名司机"
    }, {
      id: "008",
      title: "8名司机"
    }], //司机数量
    startAddress: null, //开始位置
    endAddress: null, //结束位置
    longitude: null,
    latitude: null,
    orderOrMore: true, //预约和司机数量显示
    driverCount: -1,
    pageRight: 0,
    myShow: true, //显示my的页面
    zuoyou: "icon-zuoyou", //my
    avatar: "/images/user/icon-07.png",
    buttonText: "登录",
    username: "未登录",
    orderGoing: false,
    showTimeContainer: false,
    date: ["今天", "明天", "后天"], //时间选择器
    hours: [],
    minute: [],
    homeHandlerShow: true,
    about_time: [],
    phone: "",
    make: {},
    Hmap: '',
    left_width: 750, //右边的地图
    is_distance: false



  },
  methods: {
    onLoad: function () {
      let that = this;


      wx.getSystemInfo({
        success: function (res) {
          let scale = res.screenWidth / 375;

          // 获取高度实际像素
          let screenHeight = res.screenHeight;
          console.log("屏幕screenHeight-->" + screenHeight)
          let query = wx.createSelectorQuery();
          query.select('.right_page').boundingClientRect(rect => {
            // 获取高度实际像素
            let height = rect.height;
            console.log("可见height-->" + height)
            // 将操作栏高度为500rpx 转为实际像素
            let panel_height = 500 * scale / 2;

            that.setData({
              map_height: (height - panel_height) * 2
            });
          }).exec();

        }
      })
    },
    show_left_page() {
      if (this.data.home_show_class == "home_container_right") {
        this.setData({
          home_show_class: 'home_container_left'
        })
      } else {
        this.setData({
          home_show_class: 'home_container_right'
        })
      }

    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      //获取当前位置

      let that = this;
      this.setData({
        startAddress: wx.getStorageSync("startAddress"),
        phone: wx.getStorageSync("userPhone")
      });

      if (wx.getStorageSync("endAddress") !== "") {
        this.setData({
          endAddress: wx.getStorageSync("endAddress")
        });
      }
      if (wx.getStorageSync("phonep") !== "") {
        this.setData({
          avatar: wx.getStorageSync("userMessage").avatar,
          username: wx.getStorageSync("userMessage").username,
          buttonText: wx.getStorageSync("userMessage").buttonText,
          phone: wx.getStorageSync("phonep"),
        });

        app.request({
          url: api.order.for_order,
          method: 'post',
          data: {},
          success: function (rs) {
            if (rs.code == 1) {
              if (rs.data.utype == 1) {
                wx.reLaunch({
                  url: '../../index/index'
                })
                //handler.intoPageHandler('../../index/index')
              } else if (rs.data.is_send == 0) {
                handler.intoPageHandler('../orderAndDriverGoing/orderAndDriverGoing?order_no=' + rs.data.order_no)
              } else if (rs.data.is_send == 1 && rs.data.initiate == 0 && rs.data.is_service == 0) {
                handler.intoPageHandler('../getOrderNotGoing/getOrderNotGoing?order_no=' + rs.data.order_no)
              } else if (rs.data.is_send == 1 && rs.data.initiate == 0) {
                handler.intoPageHandler('../orderGoing/orderGoing?order_no=' + rs.data.order_no)
              } else if (rs.data.initiate == 1) {
                handler.intoPageHandler('../../pay/paidOrder/paidOrder?order_no=' + rs.data.order_no)
              }
            } else {
              if (rs.data.utype == 1) {
                wx.reLaunch({
                  url: '../../index/index'
                })
                //handler.intoPageHandler('../../index/index')
              }
            }
          }
        })
      }

      // 获取屏幕信息
      this.changeIcon();
    },
    regionchange(e) {
      console.log("regionchange", e.type)
    },
    markertap(e) {
      console.log("markertap", e.markerId)
    },
    // 地图图片点击事件
    controltap(e) {
      console.log("map controltap", e.controlId)
      this.show_left_page();
      if (e.controlId === 1) {
        this.openMyPageHandler();
      } else {
        const addresses = handler.getLatLntHandler((res) => {
          //  console.log("一键定位",res);
          this.setData({
            startAddress: res.startAddress, //开始位置
          })
        });
      }
    },
    // openMyPageHandler 打开我的页面
    openMyPageHandler: function () {
      const {
        pageRight,
        myShow
      } = this.data;
      if (myShow) {
        this.setData({
          pageRight: 620,
          left_width: 130,
          myShow: !myShow,
          controls: [{
            id: 1,
            iconPath: '/images/user/icon-33.png',
            position: {
              top: 144,
              left: 10,
              width: 41,
              height: 41
            },
            clickable: true
          }],
          homeHandlerShow: false
        });
      } else {
        this.setData({
          pageRight: 0,
          left_width: 750,
          myShow: !myShow,
          controls: [{
            id: 1,
            iconPath: '/images/user/icon-22.png',
            position: {
              left: 10,
              top: 10,
              width: 50,
              height: 50
            },
            clickable: true
          }, {
            id: 2,
            iconPath: '/images/user/icon-30.png',
            position: {
              top: 240,
              left: 10,
              width: 50,
              height: 50
            },
            clickable: true
          },],
          homeHandlerShow: true
        });
        this.changeIcon()
      }
    },
    // callPhoneHandler 帮朋友叫车功能
    callPhoneHandler: function () {
      handler.intoPageHandler("../../order/helpFriendDownloadOrder/helpFriendDownloadOrder")
    },
    // getMoreDriverHandler 需要更多为司机功能
    getMoreDriverHandler: function () {
      this.setData({
        orderOrMore: !this.data.orderOrMore
      });
    },
    // bindChange 选择司机的数量
    bindChange: function (e) {
      console.log('司机数量', e.detail.value[0]);
      this.setData({
        driverCount: e.detail.value[0] + 1
      });
      console.log(this.data.driverCount)
    },
    // getDriverCountHandler 获取司机的数量
    getDriverCountHandler: function () {
      this.setData({
        orderOrMore: !this.data.orderOrMore
      });
    },
    // callServerHandler 一键呼叫事件
    callServerHandler: function () {
      if (this.data.buttonText === "登录") {
        handler.showToast('请先登录', "none")
        this.openMyPageHandler();
      } else if (this.data.endAddress === null) {
        handler.showToast('请输入目的地', "none")
      } else {
        //乘车人姓名
        var name = wx.getStorageSync("relative_people") === "" ? wx.getStorageSync("user") : wx.getStorageSync("relative_people");
        app.request({
          url: api.order.place_order,
          method: 'post',
          data: {
            startAddress: JSON.stringify(this.data.startAddress),
            endAddress: JSON.stringify(this.data.endAddress),
            driver_count: this.data.driverCount === -1 ? 1 : this.data.driverCount,
            passenger_phone: name.phone,
            passenger_name: name.name,
            paid: name.replace_pay,
            type: name.type,
            about_time: this.data.about_time,
            hours: this.data.hours,
            minute: this.data.minute,
            dat: this.data.date
          },
          success: function (rs) {
            console.log('下单成功', rs)
            if (rs.code == 1) {
              if (rs.data.orderid) {
                wx.setStorageSync("orderid", rs.data.orderid);
                wx.navigateTo({
                  url: '../orderAndDriverGoing/orderAndDriverGoing?order_no=' + rs.data.orderid
                })
                // wx.redirectTo({ });
                // handler.intoPageHandler('../orderAndDriverGoing/orderAndDriverGoing?order_no=' + rs.data.orderid)
              } else {
                handler.showToast(rs.msg, "none")
              }
            } else {
              handler.showToast(rs.msg, "none")
            }
          }
        })
      }
    },
    // orderGoingHandler 订单进行中事件
    orderGoingHandler: function () {
      handler.showToast('您还没有进行中的订单', "none")
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
      var that = this;
      //保存服务电话
      wx.setStorageSync("serverphone", "029-86263319")
      setInterval(function () {
        var list = [];
        list = wx.getStorageSync("positioning");
        console.log('获取代驾列表', list)
        if (list) {
          that.setData({
            startAddress: wx.getStorageSync("startAddress"),
          });
          //添加图标
          var make = [];
          if (wx.getStorageSync("endAddress") !== "" && wx.getStorageSync("startAddress") !== "") {
            const start = wx.getStorageSync("startAddress");
            const end = wx.getStorageSync("endAddress");
            // const make = that.data.make;
            make[make.length] = { id: make.length, iconPath: "/images/user/icon-44.png", latitude: start.location.lat, longitude: start.location.lng, width: 40, height: 40 };
            make[make.length] = { id: make.length, iconPath: "/images/user/icon-43.png", latitude: end.location.lat, longitude: end.location.lng, width: 40, height: 40 };
            make.push(list.positino);
            that.setData({
              make: make,
              startAddress: wx.getStorageSync("startAddress"),
            });
          } else {
            that.setData({ make: list.positino })
          }
        } else {
          that.setData({
            startAddress: wx.getStorageSync("startAddress"),
          });
        }
      }, 5000) //循环间隔 单位ms
      if (wx.getStorageSync("endAddress") !== "" && wx.getStorageSync("startAddress") !== "") {
        this.getPolyline(wx.getStorageSync("startAddress"), wx.getStorageSync("endAddress"))
        this.get_distance(wx.getStorageSync("startAddress"), wx.getStorageSync("endAddress"), res => {
          that.setData({ distance: (res.distance.elements[0].distance / 1000).toFixed(3), is_distance: true });
        })
        app.request({
          url: api.order.geticon,
          method: 'post',
          data: {
            start: wx.getStorageSync("startAddress").location,
            end: wx.getStorageSync("endAddress").location
          },
          success: function (rs) {
            console.log(rs, '222222')
          }
        })
      }
    },
    // 获取位置路线
    getPolyline: function (start, target) {
      let that = this;
      const { polyline } = this.data;
      // wx.setStorageSync("startAddress", { location: { lng: start.lng, lat: start.lat } });
      // wx.setStorageSync("endAddress", { location: { lng: target.lng, lat: target.lat } });
      const froms = start.location.lat + "," + start.location.lng + "&to=" + target.location.lat + "," + target.location.lng
      wx.request({
        url: `https://apis.map.qq.com/ws/direction/v1/driving/?from=${froms}&key=Z6RBZ-6H4CU-AV6V5-2OTIO-Q2CLZ-VMF5T`,
        header: {
          'content-type': 'application/json' // 默认值
        },
        success: function (res) {

          if (res.data.status === 384) { } else {
            var coors = res.data.result.routes[0].polyline;
            for (var i = 2; i < coors.length; i++) {
              coors[i] = coors[i - 2] + coors[i] / 1000000
            }
            // console.log(coors);
            const points = [];
            for (var j = 0; j < coors.length; j += 2) {
              points[points.length] = {
                longitude: coors[j + 1],
                latitude: coors[j]
              }
            }
            console.log(points)
            polyline[0].points = points;
            console.log(polyline)
            that.setData({
              polyline
            });
          }
        },
        fail: function () {
          // showToast('网络出现错误', "none")
        }
      })
    },
    // 获取距离
    get_distance: function (start, target, callback) {
      demo.calculateDistance({
        from: {
          latitude: start.location.lat,
          longitude: start.location.lng
        },
        to: [{
          latitude: target.location.lat,
          longitude: target.location.lng
        }],
        success: function (res) {
          console.log(res.result.elements[0].distance);
          callback({ distance: res.result })
        },
        fail: function (res) {
          // console.log(res);
          // console.log("*****************************")
          callback(res)
        },
        complete: function (res) {
          console.log(res);
        }
      });
    },
    // 用户信息事件
    /**loginHandler用户登录页面 */
    loginHandler: function (e) {
      if (this.data.buttonText === "登录") {
        handler.loginHandler((res) => {
          console.log("用户信息事件", wx.getStorageSync("userMessage"));
          /*this.setData({
              res,
          });*/
          const that = this;
          that.getUserInfo()
        })
      } else {
        console.log('退出登录')
        app.request({
          url: api.user.loginout,
          method: 'post',
          data: {},
          success: function (rs) {
            if (rs.code == 1) {
              wx.removeStorageSync("userMessage");
              wx.removeStorageSync("phonep");
              wx.removeStorageSync("access_token");
              wx.removeStorage({
                key: 'access_token',
              })
            }
            wx.showToast({
              title: rs.msg,
              duration: 2000
            });
          }
        })
        this.setData({
          avatar: "/images/user/icon-07.png",
          username: "未登录",
          buttonText: "登录",
          phone: ""
        });
      }
    },
    getUserInfo: function (cb) {
      handler.showModal('获取手机号码', '我们需要获取你的电话号码，一边与和你保持实时的联系，防止你的订单丢失', (ress) => {
        if (ress) {
          wx.getUserInfo({
            success: res => {
              // 登录
              wx.login({
                success: re => {
                  // 发送 res.code 到后台换取 openId, sessionKey, unionId
                  app.request({
                    url: api.user.login,
                    method: 'post',
                    data: {
                      code: re.code,
                      iv: res.iv,
                      encryptedData: res.encryptedData
                    },
                    success: function (rs) {
                      //获取到用户详细信息
                      if (rs.code == 1) {
                        wx.setStorageSync("access_token", rs.data.access_token);
                        wx.setStorageSync("phonep", rs.data.phone);
                        wx.setStorageSync("utype", rs.data.type);
                        wx.setStorageSync("price", rs.data.price);
                        if (rs.data.type == 1) {
                          wx.reLaunch({
                            url: '../../index/index'
                          })
                          /* wx.navigateTo({
                                url: '../../index/index'　　 //代驾首页
                            })*/
                        } else {
                          if (rs.data.is_binding == 1) {
                            wx.reLaunch({
                              url: './driverServer'　　 //代驾首页
                            })
                          } else {
                            wx.reLaunch({
                              url: "../../user/getPhone/getPhone",
                            })
                            // wx.redirectTo({

                            // })
                          }
                        }
                        //保存数据 用来判断是否绑定手机号
                        wx.setStorageSync('is_binding', rs.data.is_binding)
                      } else {
                        wx.removeStorage({
                          key: 'access_token',
                        })

                      }
                    }
                  })
                }
              })
            }
          })
        }
      })
    },
    // intoPageHandler 页面跳转
    intoPageHandler: function (e) {
      handler.intoPageHandler(e.currentTarget.dataset.skip);
    },
    //获取开始地址地址
    startAddress: function () {
      const that = this;
      wx.chooseLocation({
        success: function (res) {
          console.log(res)
          wx.setStorageSync("startAddress", { title: res.name, address: res.address, location: { lat: res.latitude, lng: res.longitude } })
        },
      })
    },
    //获取开始地址地址
    endAddress: function () {
      const that = this;
      wx.chooseLocation({
        success: function (res) {
          that.setData({ endAddress: { title: res.name, address: res.address, location: { lat: res.latitude, lng: res.longitude } } })
          wx.setStorageSync("endAddress", { title: res.name, address: res.address, location: { lat: res.latitude, lng: res.longitude } })
        },
      })
    },
    // relstiveServerHandler 联系客服功能
    relstiveServerHandler: function () {
      handler.callPhoneHandler(wx.getStorageSync("serverphone"));
    },
    //时间样式开始
    selectTimeShowTimeHandler: function () {
      this.setData({
        showTimeContainer: true,
        homeHandlerShow: false
      });
      this.selectTimeHandler(0, 0, 0);
    },
    // getTimeHandlerCancle 预约时间取消样式
    getTimeHandlerCancle: function () {
      this.setData({
        showTimeContainer: false,
        homeHandlerShow: true
      });
    },
    // getTimeHandlerOk 预约时间确定样式
    getTimeHandlerOk: function () {
      const { hours, minute } = this.data;
      console.log(hours, minute, '1111111111111111111');

      this.setData({
        showTimeContainer: false,
        homeHandlerShow: true
      });
    },
    // 绑定时间定时器
    bindTimeChange: function (e) {
      console.log('预约时间', e.detail.value);
      this.setData({
        about_time: e.detail.value
      })
      // 今天样式
      if (e.detail.value[0] === 0 && e.detail.value[1] === 0) {
        this.selectTimeHandler(0, 0);
      } else if (e.detail.value[0] === 0 && e.detail.value[1] !== 0) {
        this.selectTimeHandler(0, e.detail.value[1]);
      }
      // 明天和后台样式
      else if (e.detail.value[0] !== 0) {
        this.selectTimeHandler(e.detail.value[0], e.detail.value[1], 0);
      }
    },
    // 选择时间函数
    selectTimeHandler: function (dateParams, hoursParams, minutesParams) {
      const {
        hours,
        minute
      } = this.data;
      const data = new Date();
      const hour = data.getHours();
      // 今天样式
      hours.length = 0;
      minute.length = 0;
      console.log(dateParams, hoursParams, minutesParams);
      if (dateParams === 0 && hoursParams === 0) {
        hours.push("现在");
        for (var i = hour + 1; i < 24; i++) {
          hours.push(i + "点");
        }
        this.setData({
          hours,
          minute
        });
      } else if (dateParams === 0 && hoursParams !== 0) {
        hours.push("现在");
        for (var i = hour + 1; i < 24; i++) {
          hours.push(i + "点");
        }
        for (var i = 0; i < 60; i += 10) {
          minute.push(i);
        }
        this.setData({
          hours,
          minute
        });
      } else if (dateParams !== 0) {
        for (var i = 0; i < 24; i++) {
          hours.push(i + "点");
        }
        for (var i = 0; i < 60; i += 10) {
          minute.push(i);
        }
        this.setData({
          hours,
          minute
        });
      }
    },
    // 修改用户和一键定位位置
    changeIcon: function () {
      const that = this;
      const {
        controls
      } = this.data;
      wx.getSystemInfo({
        success: function success(res) {
          var controlsH = res.windowWidth / 750 * 500; //计算一像素的宽度 res.windowWidth
          var map_height = res.windowHeight - controlsH;
          controls[1] = {
            id: 2,
            iconPath: '/images/user/icon-30.png',
            position: {
              top: map_height - 56,
              left: 10,
              width: 50,
              height: 50
            },
            clickable: true
          };
          that.setData({
            winPath: {
              w: res.windowWidth,
              h: res.windowHeight
            },
            map_height,
            controls,
          });
        }
      });
    },
  },
  // 用户分享
  onShareAppMessage: function () {
    let title = app.shareAppMessage().title;
    let imageUrl = app.shareAppMessage().imageUrl;
    let desc = app.shareAppMessage().desc;
    let path = app.shareAppMessage().path;
    // console.log(app.shareAppMessage())
    return {
      title: title,
      imageUrl: imageUrl,
      desc: desc,
      path: path,
    }
  },
})
